﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;

namespace daemon
{

    class Program
    {
        #region "声明变量"

        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="section">节点名称[如[TypeName]]</param>
        /// <param name="key">键</param>
        /// <param name="val">值</param>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("kernel32")]
        public static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">节点名称</param>
        /// <param name="key">键</param>
        /// <param name="def">值</param>
        /// <param name="retval">stringbulider对象</param>
        /// <param name="size">字节大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);

        public static string strFilePath = Environment.CurrentDirectory + "\\xf.ini";//获取INI文件路径
        private static string strSec = ""; //INI文件名

        #endregion

        #region "自定义读取INI文件中的内容方法"
        /// <summary>
        /// 自定义读取INI文件中的内容方法
        /// </summary>
        /// <param name="Section">键</param>
        /// <param name="key">值</param>
        /// <returns></returns>
        public static string getValue(string Section, string key)
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
            return temp.ToString();
        }
        #endregion

        public static string name;
        public static string path;
        static protected Process[] procs;
        static void Main(string[] args)
        {
            try
            {
                Console.Title = "守护进程1.0 ~请勿关闭";
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                //读取配置文件
                //读取配置文件的exe程序
                Console.WriteLine("---------------------------------------------------");
                Console.WriteLine("-----------------定时监控进程----------------------");
                Console.WriteLine("-----------------关闭自动重启----------------------");
                Console.WriteLine("---------------------------------------------------");
                strSec = "setup";
                name = getValue(strSec, "name");
                Console.WriteLine("受监控进程：" + name);
                Console.WriteLine("---------------------------------------------------");
                //读取配置文件的exe程序的路径
                path = getValue(strSec, "path");
                Console.WriteLine("进程路径：" + path);
                Console.WriteLine("---------------------------------------------------");
                //定时监控程序状态
                //创建定时器
                //读取监控时间设置
                int seconds = Convert.ToInt32(getValue(strSec, "seconds"));
                Console.WriteLine("定时器设置：" + seconds + " 秒");
                Console.WriteLine("---------------------------------------------------");
                watchEXEStatus();
                //计时器实例化
                Timer timer = new Timer(seconds * 1000);
                //添加到了间隔时间的事件
                timer.Elapsed += timer_Elapsed;
                //计时器开始
                timer.Start();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\n\r" + ex.StackTrace);
                saveLog(ex.Message + "\n\r" + ex.StackTrace);
            }
            Console.ReadLine();
        }
        static void watchEXEStatus()
        {
            procs = Process.GetProcessesByName(name);
            //已经启动
            if (procs.Length > 0)
            {
                if (procs[0].Responding)
                    Console.WriteLine(DateTime.Now + ":" + name + " is Responding");
                else
                {
                    Console.WriteLine(DateTime.Now + ":" + name + " is Not Responding");
                    //结束进程
                    Console.WriteLine(DateTime.Now + ":" + "going to kill:" + name);
                    procs[0].Kill();
                }
            }
            //未启动
            else
            {
                Console.WriteLine(DateTime.Now + ":" + name + " is Not Running");
                Console.WriteLine(DateTime.Now + ":" + name + " is going to Run");
                System.Diagnostics.Process.Start(path);
                saveLog(name + "重启启动！");
            }
        }
        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                //逻辑判断，是否启动
                watchEXEStatus();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\n\r" + ex.StackTrace);
                saveLog(ex.Message + "\n\r" + ex.StackTrace);
            }
        }
        #region //保存执行错误的sql
        public static void saveLog(string log)
        {
            string txtName = "log";
            log = DateTime.Now.ToString() + " : " + log;
            string path = Environment.CurrentDirectory;
            if (File.Exists(path + @"\" + txtName + ".txt"))
            {
                StreamWriter SW;
                SW = File.AppendText(path + @"\" + txtName + ".txt");
                SW.WriteLine(log + "\r\n");
                SW.Close();
            }
            else
            {
                StreamWriter SW;
                SW = File.CreateText(path + @"\" + txtName + ".txt");
                SW.WriteLine(log + "\r\n");
                SW.Close();
            }

        }
        #endregion
    }
}
